"""
@Author  : 康帅
@Time    : 2021/5/5 10:16
@Function: 八种连接列表的方式
"""
from itertools import chain
from heapq import merge
from functools import reduce


def list_sum_1():
    """ 直接连接 """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = (list01 + list02 + list03)
    print(new_list_sum)


def list_sum_2():
    """ 借助 itertools """
    a1 = [1, 2, 3]
    a2 = [4, 5, 6]
    a3 = [7, 8, 9]
    a_sum = list(chain(a1, a2, a3))
    print(a_sum)


def list_sum_3():
    """ 使用 * 可以解包列表，解包后再合并 """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = [*list01, *list02, *list03]
    print(new_list_sum)


def list_sum_4():
    """ 在字典中，使用 update 可实现原地更新，而在列表中，使用 extend 可实现列表的自我扩展 """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    list01.extend(list02)
    list01.extend(list03)
    print(list01)


def list_sum_5():
    """ 使用列表推导式 """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = [x for j in (list01, list02, list03) for x in j]
    print(new_list_sum)


def list_sum_6():
    """ 使用 heapq """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = list(merge(list01, list02, list03))
    print(new_list_sum)


def list_sum_7():
    """ 借助魔法方法 __add__, reduce 这个方法来对多个列表进行合并 """
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = reduce(list.__add__, (list01, list02, list03))
    print(new_list_sum)


def list_sum_8():
    list01 = [1, 2, 3]
    list02 = [4, 5, 6]
    list03 = [7, 8, 9]
    new_list_sum = list(merges(list01, list02, list03))
    print(new_list_sum)


def merges(*lists):
    for j in lists:
        yield from j


def return_reduce():
    """
    当需要对一个列表进行一些计算并返回结果时，
    Reduce 是个非常有用的函数
    :return:
    """
    # 计算一个整数列表的乘积时
    product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
    print(product)


if __name__ == '__main__':
    list_sum_1()
    list_sum_2()
    list_sum_3()
    list_sum_4()
    list_sum_5()
    list_sum_6()
    list_sum_7()
    list_sum_8()
    return_reduce()
